import csv
import os
import time

from selenium import webdriver
from selenium.webdriver.common.by import By

# 获取当前工作目录
current_directory = os.getcwd()

# 拼接ChromeDriver路径
chrome_driver_path = os.path.join(current_directory, "chromedriver.exe")

# 设置ChromeDriver的路径
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--version=119.0.6045.160")  # 指定要模拟的Chrome版本
chrome_options.binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"  # 指定你的Chrome浏览器路径

# 创建Chrome浏览器实例
chrome_service = webdriver.ChromeService(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=chrome_service, options=chrome_options)
# driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://tianqi.2345.com/wea_history/54511.htm')
# 获取开始年份
chooseYear = driver.find_element(By.XPATH, '//*[@id="js_yearVal"]')
chooseYear.click()
startYear = driver.find_element(By.XPATH, '/html/body/div[7]/div[2]/div[1]/div[1]/div[1]/div[3]/div[1]/div/ul/li[12]/a')
startYear.click()
# 获取开始月份
chooseMonth = driver.find_element(By.XPATH, '//*[@id="js_monthVal"]')
chooseMonth.click()
startMonth = driver.find_element(By.XPATH, '/html/body/div[7]/div[2]/div[1]/div[1]/div[1]/div[3]/div[2]/div/ul/li[1]/a')
startMonth.click()
time.sleep(1)
with open('weather.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['日期', '最高温', '最低温', '天气', '风力动向'])
    for i in range(21):
        table = driver.find_element(By.XPATH, "//table[@class='history-table']")
        tbody_element = table.find_element(By.TAG_NAME, "tbody")
        rows1 = tbody_element.find_elements(By.TAG_NAME, "tr")[1::]
        rows = [row.text for row in rows1]
        for row in rows1:
            date = row.find_element(By.XPATH, "./td[1]").text
            high_temp = row.find_element(By.XPATH, "./td[2]").text
            low_temp = row.find_element(By.XPATH, "./td[3]").text
            weather = row.find_element(By.XPATH, "./td[4]").text
            wind = row.find_element(By.XPATH, "./td[5]").text
            print(row.text)
    nextMonth = driver.find_element(By.XPATH, '//*[@id="js_nextMonth"]')
    nextMonth.click()
    time.sleep(0.5)

    writer.writerow([date, high_temp, low_temp, weather, wind])
